import * as MapApi from "@/service/api/map";
import { useRectangleDialog, useMonitorTableList, useBoolean, useMouthPoly } from "@/store";
import { getAssets } from "@/utils";
const worker = new Worker(new URL("../../workers/mapDataWorker.ts", import.meta.url), { type: "module" });

const { setState } = useRectangleDialog();
const { setFooterToolShow } = useBoolean();
interface WorkerResponse {
  type: "batch" | "complete";
  data: Array<{ position: string; image: string }> | number;
}

const allValidData: Array<{ position: string; image: string }> = []; // 用于累积所有符合要求的数据

worker.addEventListener("message", (e: MessageEvent<WorkerResponse>) => {
  const { type, data } = e.data; // 解析消息类型和数据
  const { draw } = window.cesiumInit; // 获取Cesium的图元加载器实例
  if (type === "batch" && Array.isArray(data)) {
    const image = getAssets(data[0].image + "Marker.png"); // 根据数据类型获取对应的图标资源
    draw.addInPolyBillboard(data, image); // 添加标记到地图
    allValidData.push(...data.filter(item => draw.drawLayer.isInPoly(item.position)));
  } else if (type === "complete") {
    const monitorTableList = useMonitorTableList();
    monitorTableList.setState(true, type, allValidData);
  }
});
class Draw {
  map3d: any;
  selectGraphic: any;//面里面的点位
  HeatLayerPoint: any;//热力图对应得点位数据
  graphicLayer: any;
  drawLayer: any; //绘制面
  drawGLTF: any; //绘制模型

  constructor(map3d) {
    this.map3d = map3d;
    this.selectGraphic = [];
    this.HeatLayerPoint = [];
    this.drawLayer = null;
    this.drawGLTF = null;
    this.graphicLayer = new window.mars3d.layer.GraphicLayer();
    this.map3d.addLayer(this.graphicLayer);
  }

  // 添加热力图点位数据
  addData(position, attr) {
    const graphic = new window.mars3d.graphic.BillboardEntity({
      position: position,
      style: {
        horizontalOrigin: window.Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
      },
      attr,
    });
    this.graphicLayer.addGraphic(graphic);

    this.HeatLayerPoint.push(graphic);
  }

  async drawRectangle(types) {
    let data;
    const dateType = types;
    const graphic = await this.map3d.graphicLayer.startDraw({
      type: "rectangle",
      style: {
        color: "#ffff00",
        opacity: 0.1,
        clampToGround: true,
      },
    });
    this.drawLayer = graphic;
    this.updateSelect(graphic);
    if (dateType === 'monitor') { // 监控点击加载数据
      data = await MapApi.GetSearchMonitoring();
      worker.postMessage({ data, type: dateType });
    }
    this.map3d.on(window.mars3d.EventType.click, async (e) => {
      const isInArea = graphic.isInPoly(e.cartesian);
      if (!isInArea) return
      if (this.selectGraphic.length > 0) {
        const ids: any = [];
        this.selectGraphic.forEach((item: any) => {
          ids.push(...item.attr.ids);
        });

        if (dateType === 'accident' || dateType === 'deathAccident') {
          data = await MapApi.PostAccidentHeatMapDetailByReason(ids);
        } else if (dateType === 'statisticHeatMap') {
          data = ids
        } else {
          data = await MapApi.PostHeatMapDetail(dateType, ids);
        }
        setState(true, dateType, data);
        setFooterToolShow(false); //关闭底部工具栏弹窗
      }
    });
  }

  updateSelect(drawGraphic) {
    this.graphicLayer.eachGraphic((graphic) => {
      const position = graphic.positionShow;
      const isInArea = drawGraphic.isInPoly(position);
      if (isInArea) {
        this.selectGraphic.push(graphic);
      }
    });
  }

  addInPolyBillboard(positionList, image) {
    const { primitiveLoader } = window.cesiumInit;
    // 遍历所有需要渲染的位置数据
    this.drawLayer && positionList.forEach((item) => {
      // 检查当前点位是否在用户绘制的多边形区域内（通过 drawLayer 判断）
      const isInArea = this.drawLayer.isInPoly(item.position);
      if (isInArea) {
        // 在区域内则添加点标记到3D场景
        primitiveLoader.addPointPrimitive(item.position, image, item);
      }
    });
  }

  addMouthInPolyBillboard(positionList) {
    const mouthPoly = useMouthPoly();
    mouthPoly.setState();
    this.drawLayer && positionList.current.forEach((item) => {
      let position = [item.longitude, item.latitude]

      // 检查当前点位是否在用户绘制的多边形区域内（通过 drawLayer 判断）
      const isInArea = this.drawLayer.isInPoly(position);
      if (isInArea) {
        mouthPoly.currentCount += item.count
        mouthPoly.currentData.push(item.ids)
      }
    });
    this.drawLayer && positionList.last.forEach((item) => {
      let position = [item.longitude, item.latitude]

      // 检查当前点位是否在用户绘制的多边形区域内（通过 drawLayer 判断）
      const isInArea = this.drawLayer.isInPoly(position);
      if (isInArea) {
        mouthPoly.lastCount += item.count
        mouthPoly.lastData.push(item.ids)
      }
    });
  }
  removeAll() {
    this.map3d.graphicLayer.clear();
    this.selectGraphic = [];
    setState(false, '', []); //清空弹窗数据
    this.drawLayer = null;
    this.map3d.off(window.mars3d.EventType.click);
  }

  // 绘制或者删除提醒模型
  async handelOperateGLTF() {
    if (this.drawGLTF) {
      this.graphicLayer.removeGraphic(this.drawGLTF);
      this.drawGLTF = null; 0
      return false;
    } else {
      const graphic = await this.graphicLayer.startDraw({
        type: "model",
        drawShow: true, // 绘制时，是否显示模型，可避免在3dtiles上拾取坐标存在问题。
        style: {
          url: 'https://data.mars3d.cn/gltf/mars/jingche/jingche.gltf',
          scale: 24,
        }
      });
      this.drawGLTF = graphic;
      return true;
    }
  }
}

export default Draw;
